import 'package:context_menus/context_menus.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:o2oa_all_platform/common/extension/index.dart';

import '../../../../common/routers/index.dart';
import '../../../../common/style/index.dart';
import '../../../../common/utils/log_util.dart';
import '../../../../common/widgets/index.dart';
import 'index.dart';
import 'widgets/widgets.dart';

class ImChatPage extends GetView<ImChatController> {
  const ImChatPage({Key? key}) : super(key: key);

  static Future<void> open(String conversationId, {String title = ''}) async {
    await Get.toNamed(O2OARoutes.homeImChat,
        arguments: {"conversationId": conversationId, "title": title});
  }

  // 主视图
  Widget _buildView(BuildContext context) {
    return Column(
      children: [
        const Expanded(flex: 1, child: ChatMsgListWidget()),
        _bottomBarView(context)
      ],
    );
  }

  Widget _bottomBarSelectModeView(BuildContext context) {
    return SizedBox(
      height: 48,
      child: Row(children: [
        const Spacer(),
        _iconBtn(Icons.ios_share, () => controller.forwardMsgs()),
        const SizedBox(width: 10),
        _iconBtn(Icons.collections_bookmark, () => controller.collectionMsgs()),
        const Spacer(),
      ]),
    );
  }

  /// 底部操作栏
  Widget _bottomBarView(BuildContext context) {
    return Container(
        color: Theme.of(context).colorScheme.background,
        child: Column(
          children: [
            const Divider(height: 1, color: AppColor.borderColor),
            const SizedBox(height: 5),
            controller.state.isSelectMode
                ? _bottomBarSelectModeView(context)
                : Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      const SizedBox(width: 8),
                      // 桌面端不支持语音消息
                      GetPlatform.isMobile
                          ? _iconBtn(Icons.mic, controller.clickVoiceBtn)
                          : Container(),
                      Expanded(
                        flex: 1,
                        child: Padding(
                          padding: const EdgeInsets.only(left: 5, right: 5),
                          child: _inputView(context),
                        ),
                      ),
                      // _imgBtn('chat_emoji.png', controller.clickEmojiBtn),
                      // _imgBtn('chat_more_tools.png', controller.clickMoreBtn),

                      controller.state.toolBoxType == 2
                          ? _iconBtn(
                              Icons.keyboard, controller.clickShowKeyboardBtn)
                          : _iconBtn(Icons.sentiment_satisfied_alt,
                              controller.clickEmojiBtn),
                      controller.state.toolBoxType == 2
                          ? _sendBtn(context)
                          : (controller.state.showMoreTools
                              ? _iconBtn(
                                  Icons.control_point, controller.clickMoreBtn)
                              : _sendBtn(context)),
                      const SizedBox(width: 8),
                    ],
                  ),
            const SizedBox(height: 5),
            _toolView(context),
            const SizedBox(height: 5)
          ],
        ));
  }

  Widget _inputView(BuildContext context) {
    return Column(
      children: [
        TextField(
          autofocus: false,
          focusNode: controller.chatInputNode,
          contextMenuBuilder: (context, editableTextState) {
            return _buildInputViewContextMenu(context, editableTextState);
          },
          controller: controller.chatInputController,
          scrollController: controller.chatInputScrollController,
          decoration: InputDecoration(
              isDense: true,
              hintText: 'im_chat_input_hint'.tr,
              hintStyle: Theme.of(context).textTheme.bodySmall,
              filled: true,
              fillColor: Theme.of(context).colorScheme.surface,
              border: _myBorder(),
              enabledBorder: _myBorder(),
              disabledBorder: _myBorder(),
              errorBorder: _myBorder(),
              focusedErrorBorder: _myBorder(),
              focusedBorder: _myBorder()),
          style: Theme.of(context).textTheme.bodyLarge,
          // keyboardType: TextInputType.multiline,
          maxLines: 10,
          minLines: 1,
          textInputAction: TextInputAction.newline,
          // onEditingComplete: ()=>controller.onSendText(),
          // onSubmitted: (value) => controller.onSendText(),
        ),
        _quoteMsgView(context)
      ],
    );
  }

  Widget _buildInputViewContextMenu(
      BuildContext context, EditableTextState state) {
    final List<ContextMenuButtonItem> buttonItems =
        state.contextMenuButtonItems;
    final TextEditingValue value = state.textEditingValue;
    final baseOffset = value.selection.baseOffset;
    final extentOffset = value.selection.extentOffset;
    OLogger.d("baseOffset $baseOffset  extentOffset $extentOffset");
    // 判断是否有选中文字
    // if (baseOffset == extentOffset) {
    // }
    // 默认都添加换行
    buttonItems.add(ContextMenuButtonItem(
      label: 'im_chat_input_line_break'.tr,
      onPressed: () => controller.addInputLineBreak(),
    ));
    return AdaptiveTextSelectionToolbar.buttonItems(
      anchors: state.contextMenuAnchors,
      buttonItems: buttonItems,
    );
  }

  /// 引用消息
  Widget _quoteMsgView(BuildContext context) {
    return Obx(() => Visibility(
          visible: controller.state.quoteMessage.value != null,
          child: Padding(
              padding: const EdgeInsets.only(top: 5),
              child: Container(
                decoration: BoxDecoration(
                  color: AppColor.imQuoteMsgColor,
                  borderRadius: BorderRadius.circular(4),
                ),
                padding: const EdgeInsets.only(left: 5, right: 5),
                child: Row(children: [
                  Expanded(
                      flex: 1,
                      child: Text(
                        '${controller.state.quoteMessage.value?.createPerson?.o2NameCut()}: ${controller.state.quoteMessage.value?.toBody()?.conversationBodyString()}',
                        style: Theme.of(context).textTheme.bodySmall,
                      )),
                  const SizedBox(width: 5),
                  IconButton(
                      onPressed: () => controller.deleteQuoteMsg(),
                      icon: const Icon(Icons.close, size: 16),
                      padding: EdgeInsets.zero,
                      constraints: const BoxConstraints())
                ]),
              )),
        ));
  }

  /// 工具区域
  /// 显示扩展工具、表情、语音发送等工具的区域
  Widget _toolView(BuildContext context) {
    return Container(
        color: Theme.of(context).scaffoldBackgroundColor,
        child: Obx(() {
          if (controller.state.toolBoxType == 1) {
            // 语音
            return const SizedBox(
              height: 150,
              width: double.infinity,
              child: ImVoiceRecordToolView(),
            );
          } else if (controller.state.toolBoxType == 2) {
            // 表情
            return const SizedBox(
              height: 250,
              width: double.infinity,
              child: EmojiTextListWidget(),
            );
          } else if (controller.state.toolBoxType == 3) {
            // 更多
            return const SizedBox(
              height: 100,
              width: double.infinity,
              child: ImMoreToolListWidget(),
            );
          }
          return Container();
        }));
  }

  Widget _imgBtn(String assetsImageName, GestureTapCallback tap) {
    return SizedBox(
      width: 36,
      height: 36,
      child: InkWell(
        onTap: tap,
        child: AssetsImageView(assetsImageName),
      ),
    );
  }

  /// 按钮
  Widget _iconBtn(IconData icon, GestureTapCallback tap) {
    return IconButton(onPressed: tap, icon: Icon(icon, size: 36));
  }

  Widget _sendBtn(BuildContext context) {
    return ElevatedButton(
        onPressed: () => controller.onSendText(),
        child:  Text("im_chat_menu_send".tr)
      );
  }

  /// 输入框样式
  OutlineInputBorder _myBorder() {
    return OutlineInputBorder(
        borderRadius: BorderRadius.circular(50),
        borderSide: const BorderSide(color: AppColor.borderColor));
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ImChatController>(
      builder: (_) {
        return Obx(() => O2UI.basePopScope(
            child: Scaffold(
                appBar: controller.state.isSelectMode
                    ? AppBar(
                        automaticallyImplyLeading: false,
                        title: Row(
                          mainAxisAlignment: MainAxisAlignment.start,
                          children: [
                            TextButton(
                              onPressed: () => controller.cancelMultiSelect(),
                              child: Text('cancel'.tr,
                                  style: AppTheme.whitePrimaryTextStyle),
                            ),
                            Expanded(
                                flex: 1,
                                child:
                                    Center(child: Text(controller.state.title)))
                          ],
                        ))
                    : AppBar(
                        title: Text(controller.state.title),
                        actions: [
                          PopupMenuButton(
                            itemBuilder: (ctx) {
                              return controller.state.menuList.map((element) {
                                return PopupMenuItem(
                                  child: Text(element.name),
                                  onTap: () =>
                                      controller.clickActionMenu(element),
                                );
                              }).toList();
                            },
                          )
                        ],
                      ),
                body: SafeArea(
                  child: ContextMenuOverlay(
                      cardBuilder: (_, children) => Container(
                            decoration: BoxDecoration(
                                borderRadius: BorderRadius.circular(4),
                                color: Colors.black87),
                            child: Flex(
                                direction: children.length > 4
                                    ? Axis.vertical
                                    : Axis.horizontal,
                                children: children),
                          ),

                      /// Make custom buttons
                      buttonBuilder: (_, config, [__]) => TextButton(
                            onPressed: config.onPressed,
                            child: Text(config.label,
                                style: AppTheme.whitePrimaryTextStyle),
                          ),
                      child: Container(
                        color: Theme.of(context).scaffoldBackgroundColor,
                        child: GestureDetector(
                            onTap: controller.closeSoftInputAndOtherTools,
                            child: _buildView(context)),
                      )),
                ))));
      },
    );
  }
}
